const User = require('../models/user.model');
const AppError = require('../utils/AppError');
const bcrypt = require('bcryptjs');
const speakeasy = require('speakeasy');
const qrcode = require('qrcode');

// 修改邮箱
exports.updateEmail = async (req, res, next) => {
  const { newEmail, password } = req.body;
  const userId = req.user._id;

  try {
    const user = await User.findById(userId);
    if (!user) {
      return next(new AppError('用户不存在', 404));
    }

    // 验证当前密码
    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      return next(new AppError('密码不正确', 400));
    }

    // 检查新邮箱是否已被使用
    const existingUser = await User.findOne({ email: newEmail });
    if (existingUser && !existingUser._id.equals(userId)) {
      return next(new AppError('该邮箱已被其他用户使用', 400));
    }

    // 更新邮箱 (可能需要发送验证邮件)
    user.email = newEmail;
    user.isVerified = false; // 如果需要邮箱验证，重置验证状态
    await user.save();

    res.json({ message: '邮箱更新成功，请检查您的新邮箱进行验证', email: user.email });

  } catch (error) {
    console.error('修改邮箱失败:', error);
    next(new AppError('修改邮箱失败', 500));
  }
};

// 修改密码
exports.updatePassword = async (req, res, next) => {
  const { currentPassword, newPassword } = req.body;
  const userId = req.user._id;

  try {
    const user = await User.findById(userId);
    if (!user) {
      return next(new AppError('用户不存在', 404));
    }

    // 验证当前密码
    const isMatch = await user.comparePassword(currentPassword);
    if (!isMatch) {
      return next(new AppError('当前密码不正确', 400));
    }

    // 更新密码 (模型 pre-save 钩子会自动哈希)
    user.password = newPassword;
    await user.save();

    res.json({ message: '密码更新成功' });

  } catch (error) {
    console.error('修改密码失败:', error);
    next(new AppError('修改密码失败', 500));
  }
};

// 获取两步验证设置状态和二维码
exports.getTwoFactorSetup = async (req, res, next) => {
  const userId = req.user._id;

  try {
    const user = await User.findById(userId);
    if (!user) {
      return next(new AppError('用户不存在', 404));
    }

    if (user.twoFactorEnabled) {
      return res.json({ enabled: true });
    }

    // 生成新的 secret
    const secret = speakeasy.generateSecret({ length: 20, name: `MedioTube (${user.email})` });
    user.twoFactorSecret = secret.base32;
    await user.save();

    // 生成二维码 URL
    qrcode.toDataURL(secret.otpauth_url, (err, data_url) => {
      if (err) {
        console.error('生成二维码失败:', err);
        return next(new AppError('生成二维码失败', 500));
      }
      res.json({ enabled: false, qrCodeUrl: data_url, secret: secret.base32 });
    });

  } catch (error) {
    console.error('获取两步验证设置失败:', error);
    next(new AppError('获取两步验证设置失败', 500));
  }
};

// 启用两步验证
exports.enableTwoFactor = async (req, res, next) => {
  const { token } = req.body;
  const userId = req.user._id;

  try {
    const user = await User.findById(userId);
    if (!user || !user.twoFactorSecret) {
      return next(new AppError('请先获取两步验证设置', 400));
    }

    // 验证 OTP token
    const verified = speakeasy.totp.verify({
      secret: user.twoFactorSecret,
      encoding: 'base32',
      token: token,
      window: 1 // 允许前后一个时间窗口的容错
    });

    if (!verified) {
      return next(new AppError('无效的两步验证码', 400));
    }

    user.twoFactorEnabled = true;
    await user.save();

    res.json({ message: '两步验证已成功启用' });

  } catch (error) {
    console.error('启用两步验证失败:', error);
    next(new AppError('启用两步验证失败', 500));
  }
};

// 禁用两步验证
exports.disableTwoFactor = async (req, res, next) => {
  const { password } = req.body; // 禁用时需要验证密码
  const userId = req.user._id;

  try {
    const user = await User.findById(userId);
    if (!user) {
      return next(new AppError('用户不存在', 404));
    }

    // 验证密码
    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      return next(new AppError('密码不正确', 400));
    }

    user.twoFactorEnabled = false;
    user.twoFactorSecret = undefined; // 清除 secret
    await user.save();

    res.json({ message: '两步验证已禁用' });

  } catch (error) {
    console.error('禁用两步验证失败:', error);
    next(new AppError('禁用两步验证失败', 500));
  }
};